package cn.kgc.tangcco.interceptor;

import cn.kgc.tangcco.model.ResponseText;
import cn.kgc.tangcco.model.ResultCode;
import cn.kgc.tangcco.pojo.Account;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 李昊哲
 * @Description 鉴权
 * @create 2020/12/31 9:04
 */
@Configuration
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authentication");
        if (StringUtils.isEmpty(token)) {
            printJson(response,new ResponseText(ResultCode.PARAM_ERROR.getCode(), ResultCode.PARAM_ERROR.getMsg(), null));
            return false;
        }else if (!stringRedisTemplate.hasKey(token)) {
            printJson(response,new ResponseText(ResultCode.NO_LOGIN.getCode(), ResultCode.NO_LOGIN.getMsg(), null));
            return false;
        }else{
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * 响应字符串
     *
     * @param response HttpServletResponse
     * @param text     响应的字符串
     * @throws IOException IOException
     */
    public void printText(HttpServletResponse response, String text) throws IOException {
        PrintWriter writer = response.getWriter();
        writer.println(text);
        writer.flush();
        writer.close();
    }

    /**
     * 响应对象的json字符串
     *
     * @param response HttpServletResponse
     * @param object   返回的对象
     * @throws IOException IOException
     */
    public void printJson(HttpServletResponse response, Object object) throws IOException {
        printText(response, JSON.toJSONString(object));
    }

}
